import { useState, useEffect, useMemo } from "preact/hooks";
import { settings } from "../settings";
import { checkImage } from "../utilities";
import { isExternalFavoUrl, parseExternalFavoUrl } from "../Vendor";

const Favo = ({ box }) => {
  const [hasIcon, setHasIcon] = useState(false);
  const target = useMemo(
    () =>
      settings.value.favo.newTab && isExternalFavoUrl(box.url)
        ? "_blank"
        : "_self",
    [box],
  );
  const url = useMemo(() => parseExternalFavoUrl(box.url), [box]);

  useEffect(() => {
    if (box.image !== "") {
      checkImage(box.image)
        .then(() => {
          setHasIcon(true);
        })
        .catch(() => {
          setHasIcon(false);
        });
    }
  }, [box.image]);

  return (
    <div
      class="m-[0] block text-center"
      style={{
        width: settings.value.favo.size,
        height: `calc(${String(settings.value.favo.size)}px${settings.value.favo.showTitle ? " + 1.25rem" : ""})`,
      }}
    >
      <a href={url} target={target} rel="noopener noreferrer">
        {hasIcon ? (
          <div class="avatar" aria-hidden="true">
            <div
              style={{
                width: settings.value.favo.size,
                borderRadius:
                  (settings.value.favo.size / 2) * settings.value.favo.radius,
                background: `center / contain no-repeat url("${box.image}")`,
              }}
            />
          </div>
        ) : (
          <div class="avatar avatar-placeholder" aria-hidden="true">
            <div
              class={`${!settings.value.favo.borderStyle && box.color === "" ? "bg-neutral" : ""} ${settings.value.favo.borderStyle ? "" : "text-neutral-content"}`}
              style={{
                width: settings.value.favo.size,
                borderRadius:
                  (settings.value.favo.size / 2) * settings.value.favo.radius,
                backgroundColor:
                  settings.value.favo.borderStyle || box.color === ""
                    ? void 0
                    : box.color,
                color: settings.value.favo.borderStyle
                  ? box.color || "#6f8de1"
                  : void 0,
                boxShadow: settings.value.favo.borderStyle
                  ? `0 0 0 2px inset ${box.color || "#6f8de1"}`
                  : void 0,
              }}
            >
              <span class="p-[0]">
                {String.fromCodePoint(box.title.codePointAt(0))}
              </span>
            </div>
          </div>
        )}
        {settings.value.favo.showTitle ? (
          <p
            class="mt-px h-5 overflow-hidden text-xs/5 wrap-anywhere break-all text-clip"
            aria-hidden="true"
            style={{ width: settings.value.favo.size }}
          >
            {box.title}
          </p>
        ) : (
          void 0
        )}
      </a>
    </div>
  );
};

export default Favo;
